package com.baize.markwondemo.spans;

import android.graphics.BlurMaskFilter;
import android.graphics.Color;
import android.graphics.ColorFilter;
import android.graphics.EmbossMaskFilter;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffColorFilter;
import android.graphics.PorterDuffXfermode;
import android.graphics.Shader;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.util.Log;
import android.view.View;

import androidx.annotation.ColorInt;
import androidx.annotation.NonNull;

import java.util.concurrent.atomic.AtomicBoolean;

public class MaskTextSpan extends ClickableSpan {

  //遮挡颜色
  private int mask_color;
  //遮挡状态
  private AtomicBoolean hideState;
  //Span唯一标志（文字内容的Hash值）
  private int flag;

  public MaskTextSpan() {
    this(Color.parseColor("#AEAEB4"), -1);
  }

  public MaskTextSpan(int flag) {
    this(Color.parseColor("#AEAEB4"), flag);
  }

  public MaskTextSpan(@ColorInt int maskColor, int flag) {
    this.flag = flag;
    this.mask_color = maskColor;
    this.hideState = new AtomicBoolean(MaskTextSpanStateManager.getInstance().get(flag));
    Log.i("baize_", "spanFlag:" + flag + " state:" + hideState);
  }

  public boolean getHideState() {
    return hideState.get();
  }

  @Override
  public void updateDrawState(@NonNull TextPaint ds) {
    //Returns "this" for most CharacterStyles, but for CharacterStyles that were generated by wrap, returns the underlying CharacterStyle.
//    super.updateDrawState(ds);
    Log.i("baize", "updateDrawState...");
    if (hideState.get()) {
      ds.setColor(Color.TRANSPARENT);
      ds.bgColor = mask_color;
      ds.linkColor = Color.TRANSPARENT;
      ds.setTextSkewX(0f);
//      ds.setMaskFilter(new BlurMaskFilter(20, BlurMaskFilter.Blur.NORMAL));
      ColorFilter colorFilter = new PorterDuffColorFilter(Color.parseColor("#AEAEB4"), PorterDuff.Mode.SRC_OVER);
      ds.setColorFilter(colorFilter);
//      ds.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST));
    } else {
      ds.setColor(ds.getColor());
      ds.bgColor = Color.TRANSPARENT;
//      ds.setMaskFilter(null);
    }
    ds.clearShadowLayer();
    // 去除下划线
    ds.setUnderlineText(false);
  }

  @Override
  public void onClick(@NonNull View widget) {
    MaskTextSpanStateManager.getInstance().cache(flag, !hideState.get());
    hideState.set(!hideState.get());
    widget.invalidate(widget.getLeft(), widget.getTop(), widget.getRight(), widget.getBottom());
//    widget.invalidate();
  }
}
